package cookie.share.web;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cookie.share.util.CookieUtil;

/**
 * @comment
 * @date 2015年11月19日 下午5:34:45
 * @author zhouxiao
 * @qq 772716714
 * @version 1.0
 */
public class CookieServlet extends HttpServlet {

	private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss] ");

	private static final String COOKIE_NAME = "zhouxiao";

	private static final String COOKIE_VALUE = "cookie test for firefox";

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String param = request.getParameter("cookie");
		if ("init".equals(param)) {
			//测试1
			//CookieUtil.addCookie(response, COOKIE_NAME, COOKIE_VALUE, "/", 0);
			//测试2
			//CookieUtil.addCookie(response, COOKIE_NAME, COOKIE_VALUE, "/",".osj.com", 0);
			//测试3
			CookieUtil.setHeader(response);
			CookieUtil.addCookie(response, COOKIE_NAME, COOKIE_VALUE, "/",".n.com", 0);
			System.out.println(simpleDateFormat.format(new Date()) + " cookie init completed.");
		} else if ("test".equals(param)) {
			Cookie cookie = CookieUtil.getCookieByName(request, COOKIE_NAME);
			if (cookie != null) {
				request.setAttribute("cookieName", cookie.getName());
				request.setAttribute("cookieValue", cookie.getValue());
			}
		}
		request.getRequestDispatcher("/index.jsp").forward(request, response);
	}
}
